<?php
namespace app\user\controller;
use app\common\model\Comment;
use app\common\model\Express;
use app\common\model\Merchant as MerchantModel;
use app\common\model\Comment as CommentModel;
use app\common\model\Order as OrderModel;
use think\Exception;
use think\facade\Session;
use think\db;

/**
 * 订单操作控制器
 * Class Operate
 * @package app\user\controller\order
 */
class Merchant extends Controller
{
    /* @var OrderModel $model */
    private $model;

    private $delete_type = [1=>'未审核',2=>'审核通过',3=>'审核不通过',4=>'已删除',5=>'休息中'];


    /**
     * 商铺列表
     */
    public function index()
    {
        $delete_type = $this->delete_type;
        $houtai = Session::get('houtaizhuangtai');
        if(!empty($houtai)&&$houtai ==1){
            $model = new MerchantModel;
            $where['merchant_user_id'] = Session::get('wymall_store.user_id');
            $where['state'] = '2';
            $merchant = $model->zhanghaodan($where);
            $type = 'shoudetail';
            $delete_type = $this->delete_type;
            $detail=$model::shoudetail($merchant['merchant_id']);
            $where = [];$wherea=[];$whereb=[];
            $where['province_id'] = $detail['province_id'];
            $province = $model->citylist($where);
            !empty($province)?$detail['provincename'] = $province['name']:$detail['provincename']='';
            $wherea['city_id'] = $detail['city_id'];
            $citylist = $model->citylist($wherea);
            !empty($citylist)?$detail['cityname'] = $citylist['name']:$detail['cityname']='';
            $whereb['district_id'] = $detail['district_id'];
            $district = $model->citylist($whereb);
            !empty($district)?$detail['districtname'] = $district['name']:$detail['districtname'] ='';
            return $this->fetch($type,compact('detail','delete_type'));
        }
        $model = new MerchantModel;
        $list = $model->getlist($this->request->post(),'2');
        if(count($list)>0)
        {
            foreach ($list as $key=>$value)
            {
                $where = [];$wherea=[];$whereb=[];
                $where['province_id'] = $value['province_id'];
                $province = $model->citylist($where);
                !empty($province)?$list[$key]['provincename'] = $province['name']:$list[$key]['provincename']='';
                $wherea['city_id'] = $value['city_id'];
                $citylist = $model->citylist($wherea);
                !empty($citylist)?$list[$key]['cityname'] = $citylist['name']:$list[$key]['cityname']='';
                $whereb['district_id'] = $value['district_id'];
                $district = $model->citylist($whereb);
                !empty($district)?$list[$key]['districtname'] = $district['name']:$list[$key]['districtname'] ='';

            }
        }
        return $this->fetch('shoulist', compact('list','delete_type'));
    }

    /**
     * 商铺详情
     * @param $order_id
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function shoudetail($merchant_id,$type)
    {
        $model = new MerchantModel;
        $delete_type = $this->delete_type;
        $detail=$model::shoudetail($merchant_id);
        $where = [];$wherea=[];$whereb=[];
        $where['province_id'] = $detail['province_id'];
        $province = $model->citylist($where);
        !empty($province)?$detail['provincename'] = $province['name']:$detail['provincename']='';
        $wherea['city_id'] = $detail['city_id'];
        $citylist = $model->citylist($wherea);
        !empty($citylist)?$detail['cityname'] = $citylist['name']:$detail['cityname']='';
        $whereb['district_id'] = $detail['district_id'];
        $district = $model->citylist($whereb);
        !empty($district)?$detail['districtname'] = $district['name']:$detail['districtname'] ='';
        return $this->fetch($type,compact('detail','delete_type'));

    }

    public function initialize()
    {
        parent::initialize();
        $this->model = new MerchantModel;
    }
    /**
     * 导出
     * @param string $dataType
     * @throws \think\exception\DbException
     */
    public function export($dataType)
    {
        $model = new OrderModel;
        $info = $this->request->post();
        if(empty($info)){
            $info['dataTypead'] = 'All';
        }
        $dataType = $dataTypead =$info['dataTypead'];
        $state = 2;
        $list = $model->pcgetLists($dataTypead, $info,$state);

        // 表格标题
        $tileArray = ['订单号', '商品名称', '单价', '数量', '付款金额', '运费金额', '下单时间',
            '买家', '买家留言', '收货人姓名', '联系电话', '收货人地址', '物流公司', '物流单号',
            '付款状态', '付款时间', '发货状态', '发货时间', '收货状态', '收货时间', '订单状态',
            '微信支付交易号', '是否已评价'];
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            /* @var OrderAddress $address */
            $address = $order['address'];
            foreach ($order['goods'] as $Item) {
                $dataArray[] = [
                    '订单号' => $this->filterValue($order['order_no']),
                    '商品名称' => $Item['name'],
                    '单价' => $Item['goods_price'],
                    '数量' => $Item['total_num'],
                    '付款金额' => $this->filterValue($order['pay_price']),
                    '运费金额' => $this->filterValue($order['express_price']),
                    '下单时间' => $this->filterValue($order['create_time']),
                    '买家' => $this->filterValue($order['user']['nickName']),
                    '买家留言' => $this->filterValue($order['buyer_remark']),
                    '收货人姓名' => $this->filterValue($order['address']['name']),
                    '联系电话' => $this->filterValue($order['address']['phone']),
                    '收货人地址' => $this->filterValue($address ? $address->getFullAddress() : ''),
                    '物流公司' => $this->filterValue($order['express']['express_name']),
                    '物流单号' => $this->filterValue($order['express_no']),
                    '付款状态' => $this->filterValue($order['pay_status']['text']),
                    '付款时间' => $this->filterTime($order['pay_time']),
                    '发货状态' => $this->filterValue($order['delivery_status']['text']),
                    '发货时间' => $this->filterTime($order['delivery_time']),
                    '收货状态' => $this->filterValue($order['receipt_status']['text']),
                    '收货时间' => $this->filterTime($order['receipt_time']),
                    '订单状态' => $this->filterValue($order['order_status']['text']),
                    '微信支付交易号' => $this->filterValue($order['transaction_id']),
                    '是否已评价' => $this->filterValue($order['is_comment'] ? '是' : '否'),
                ];
            }
        }
        // 导出csv文件
        $filename = 'order-' . date('YmdHis');
        return export_excel($filename . '.csv', $tileArray, $dataArray);
    }
    /**
     * 批量
     */
    public function deliveryTpl()
    {
        return $this->model->deliveryTpl();
    }

    /**
     * 删除数据
     * @param $id
     * @param $table
     * @return array
     */
    public function uptatead($id='',$table='1')
    {

        if(!empty($id)){
            $model = new MerchantModel;
            if($table == 'uptatead'){
                $table = '2';
            }
            if($table == 'uptatecd'){
                $table = '3';
            }
            if($table == 'deletead'){
                $table = '4';
            }
            if($table == 'deletecd'){
                $table = '2';
            }
            $info = $model->saveMerchant($id,$table);
            if($info){
                return $this->renderSuccess('修改成功');
            }
            return $this->renderError($model->getError() ?: '修改失败');
        }
    }

    /**
     * 商品列表(出售中)
     */
    public function items($status = null, $category_id = null, $name = '', $market = '')
    {
        // 商品分类
        //$catgory = (new CategoryModel)->getSortCategory();
        $catgory= '';
        // 商品列表
        $model = new \app\common\model\Item();
        $state = 2;
        $list = $model->pcgetList($state,$status, $category_id, $name,$market);

        /*if(count($list['data'])>0){
            foreach ($list['data'] as $key=>$vavel){
                $list['data'][$key]['create_timead'] = date('Y-m-d H:i',$vavel['create_time']);
            }
        }*/
        if(empty($market)){
            return $this->fetch('index', compact('list'));
        }
        return $this->fetch('goodslist', compact('list'));
    }

    /**
     * 商品编辑
     */
    public function pcedit($goods_id='')
    {
        $model = new \app\common\model\Item();
        $data=$this->request->post();
        $state = 2;
        if (!$this->request->isAjax()) {
            $goodsInfo=$model::pcdetailad($goods_id);
            $arr_imge = $model::detailimg($goods_id);
            // 商品分类
            /*  $itemType = (new TypeModel)->All();
             $brandList = (new ItemModel)->getSortBrands();//获取品牌
             $delivery = DeliveryModel::getAll();*/
            //sku和分类
            $province = $model->provinceList();
            $citylist = '';
            if(!empty($goodsInfo['province_id'])){
                $citylist = $model->cityList($goodsInfo['province_id']);
            }
            $dislist='';
            if(!empty($goodsInfo['city_id'])){
                $dislist = $model->districtList($goodsInfo['city_id']);
            }
            return $this->fetch('edit', compact('goodsInfo','arr_imge','province','citylist','dislist'));
        }
        if ($goods_id?$model->pcedit($data,$state):$model->pcaddGood($data,$state)) {

            return $this->renderSuccess('更新成功', url('merchant/items'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

    /**
     * 评价列表
     */
    public function comment($item_id = null,$user_id = null)
    {
        $info = $this->request->route();
        $model = new \app\common\model\Order();
        $model2 = new \app\common\model\Item();
        if(empty($info['goods_id'])){
            $info['goods_id'] = '';
        }
        $state = 2;
        $list = $model->pcpingjialist($info['goods_id'],$state);
        return $this->fetch('comment', compact('list'));
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        $info = $this->request->post();
        $model = new \app\common\model\Order();
        if($model->setDelete($info['id'])){
        return $this->renderSuccess('成功');
        }
        return $this->renderError('失败');
    }

    /**
     * 订单列表
     */
    public function order()
    {
        $model = new \app\common\model\Order();
        $info = $this->request->post();
        if(empty($info)){
            $info['dataTypead'] = 'All';
        }
        $dataType = $dataTypead =$info['dataTypead'];
        $state = 2;
        $list = $model->pcgetLists($dataTypead, $info,$state);
        $title = '全部';
        return $this->fetch('order', compact('title', 'dataType', 'list','dataTypead'));
    }


    /**
     * 订单详情
     * @param $order_id
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $info = $this->request->route();

        $model=new \app\common\model\Order();
        $where['order_id'] = $info['order_id'];
        $detail=$model::detail($info['order_id']);

        return $this->fetch('detail',compact('detail'));

    }

    /**
     * 列表
     */
    public function tuandui($name = '')
    {
        $houtai = Session::get('houtaizhuangtai');
        if(!empty($houtai)&&$houtai ==1){
            $where['a.merchant_pid']=self::$user_id;
        }
        if(!empty($name)){
            $where['b.merchant_name']=$name;
        }
        $where['a.state']=2;
        $state = 2;
        $list = (new \app\common\model\MerchantTeam())->pctuanduilist($where,$state);

        return $this->fetch('tuanduilist', compact('list'));
    }

    /**
     * 下级列表
     */
    public function xialists()
    {
        $data = $this->request->post();
        if(empty($data['id'])){
            return $this->renderError('缺少必须参数',1001);
        }
        $where['merchant_id'] = $data['id'];
        $use = new \app\common\model\User();
        $uer = $use->detailShang($where);
        $model = new MerchantTeamModel();
        $list = $model->xialists($data['id']);
        if(!empty($uer['logo'])){
            $uer['logoad'] = '/uploads/'.$uer['logo'].'.jpg';
        }else{
            $uer['logoad'] = '';
        }
        if(count($list)>0){
            foreach ($list as $key=>$value){
                if(!empty($value['logo'])){
                    $list[$key]['logoad'] = '/uploads/'.$value['logo'].'.jpg';
                }else{
                    $list[$key]['logoad'] = '';
                }
            }
        }
        $info['user'] = $uer;
        $info['list'] = $list;
        $info['sum'] = count($list);

        return $this->renderSuccess('成功',$info);
    }
    /*
         * 团队删除
         * */
    public function tuanduidelete()
    {
        $model = (new \app\common\model\MerchantTeam());
        $data=$this->request->post();
        if ($model->shejisdelete($data['id'])) {
            return $this->renderSuccess('成功', url('merchant/tuandui'));
        }
        $error = $model->getError() ?: '失败';
        return $this->renderError($error);
    }

    /**
     * 商品编辑
     */
    public function renovationedit($merchant_id='')
    {
        $model = new \app\common\model\Item();
        $data=$this->request->post();
        $state = '1';
        if (!$this->request->isAjax()) {
            $goodsInfo=Db::table('bfb_merchant')->where(['merchant_id'=>$merchant_id])->find();
            $arr_imge = $model::detailimg($merchant_id);
            // 商品分类
            /*  $itemType = (new TypeModel)->All();
             $brandList = (new ItemModel)->getSortBrands();//获取品牌
             $delivery = DeliveryModel::getAll();*/
            //sku和分类
            $province = $model->provinceList();
            $citylist = '';
            if(!empty($goodsInfo['province_id'])){
                $citylist = $model->cityList($goodsInfo['province_id']);
            }
            $dislist='';
            if(!empty($goodsInfo['city_id'])){
                $dislist = $model->districtList($goodsInfo['city_id']);
            }

            return $this->fetch('renovationedit', compact('goodsInfo','arr_imge','province','citylist','dislist'));
        }

        if($merchant_id){
            $list = Db::table('bfb_merchant')->where(['merchant_id'=>$merchant_id])->update($data);
        }else{
            $info =  Db::table('bfb_merchant_user')->where(['phone'=>$data['phone']])->find($data);
            if($info){
                $data['merchant_user_id'] = $info['merchant_id'];
                $data['state'] = 2;
                $list = Db::table('bfb_merchant')->insert($data);
            }else{
                $asda['phone'] = $data['phone'];
                $asda['password'] = md5($data['phone']);
                $menid =  Db::table('bfb_merchant_user')->insertGetId($asda);
                $data['merchant_user_id'] = $menid;
                $data['state'] = 2;
                $list = Db::table('bfb_merchant')->insert($data);
            }
        }
        if($list){
            return $this->renderSuccess('更新成功', url('merchant/index'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

}